package com.rpc.netty.groupChartNetty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @author 何章怀晓 hezhanghuaixiao
 * @version V1.0
 * @desc
 */
public class GroupChartClient {

  private final int port;

  private final String addr;

  public GroupChartClient(int port, String addr) {
    this.port = port;
    this.addr = addr;
  }

  public void run() {
    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    try {

      Bootstrap bootstrap = new Bootstrap();
      bootstrap.group(eventLoopGroup)
          .channel(NioSocketChannel.class)
          .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
              ChannelPipeline pipeline = ch.pipeline();
              System.out.println("客户端pipeline" + pipeline.hashCode());
              //解码编码
              pipeline.addLast("decofer", new StringDecoder());
              pipeline.addLast("encoder", new StringEncoder());
              pipeline.addLast(new GroupChartClientHandler());
            }
          });
      ChannelFuture sync = bootstrap.connect(addr, port).sync();
      Channel channel = sync.channel();

      System.out.println("客户端上线了" + channel.remoteAddress());

      Scanner scanner = new Scanner(System.in);
      while (scanner.hasNextLine()) {
        String msg = scanner.nextLine();
        channel.writeAndFlush(msg);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      eventLoopGroup.shutdownGracefully();
    }

  }

  public static void main(String[] args) {
    new GroupChartClient(8888, "localhost").run();
  }


}
